package com.secret.chain.secretchain.controller.wx;
import com.secret.chain.secretchain.domain.dto.UserLoginDTO;
import com.secret.chain.secretchain.domain.entity.User;
import com.secret.chain.secretchain.domain.vo.UserLoginVO;
import com.secret.chain.secretchain.propreties.JwtProperties;
import com.secret.chain.secretchain.result.Result;
import com.secret.chain.secretchain.service.UserService;
import com.secret.chain.secretchain.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/wx/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    @PostConstruct
    public void init() {
        log.info("JwtProperties loaded: {}", jwtProperties);
    }

    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("微信用户登录：{}", userLoginDTO.getCode());

        // 微信登录
        User user = userService.wxLogin(userLoginDTO);

        // 为微信用户生成 JWT 令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getId());

        // 确保 userTtl 不为空
        Long userTtl = jwtProperties.getUserTtl();
        if (userTtl == null) {
            userTtl = 3600000L; // 默认1小时（毫秒）
            log.warn("JwtProperties.userTtl is null, using default value: {} ms", userTtl);
        }

        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), userTtl, claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();

        return Result.success(userLoginVO);
    }

    @GetMapping("/{id}")
    public Result<User> queryById(@PathVariable Integer id) {
        User user = userService.queryById(id);
        return Result.success(user);
    }

    @PutMapping()
    public Result<Void> updateUserInfo(@RequestBody User user) {
        userService.updateUserInfo(user);
        return Result.success();
    }
}